import { setWebIcon } from "@/utils/utils"

const cacheNames = ["pageTitle"]

export default {
  state: {
    baseInfo: {
      couponCardMergeUse: 0
    }, // 基础信息
    couponCardMergeUse: false, // 卡券是否可以同时使用
    realNameStatus: "0", // 实名设置：0-无需实名，1-实名一一对应，2-至少一份实名
    realNameAg: "", // 实名通知内容
    baseInfoReady: false,
    pageTitle: ""
  },
  getters: {
    baseInfo: (state) => state.baseInfo,
    pageTitle: (state) => state.pageTitle,
    realNameStatus: (state) => state.realNameStatus,
    realNameAg: (state) => state.realNameAg,
    couponCardMergeUse: (state) => state.baseInfo.couponCardMergeUse == 1,
    cardName: (state) => {
      let cardName = "电影卡"
      if (state.baseInfo?.cardNameType == 2 && state.baseInfo?.cardName) cardName = state.baseInfo.cardName
      return cardName
    }
  },
  mutations: {
    // 自动初始化
    INIT(state) {
      // 初始化本地缓存
      cacheNames.forEach((name) => {
        let data = uni.getStorageSync(name)
        if (data) state[name] = data
      })
    },
    //  设置基础信息
    SET_BASE_INFO(state, data) {
      if (data) {
        state.realNameStatus = data.realNameStatus
        state.realNameAg = data.realNameAg
        state.baseInfo = data
        uni.setStorageSync("baseInfo", data)
      }
      state.baseInfoReady = true
    },
    //  设置页面标题
    SET_PAGE_TITLE(state, data) {
      state.pageTitle = data
      uni.setStorageSync("pageTitle", data)
    },
    //  清除基础信息
    CLEAR_BASE_INFO(state) {
      state.realNameStatus = "0"
      state.realNameAg = ""
      state.baseInfo = {
        couponCardMergeUse: 0
      }
      uni.removeStorageSync("baseInfo")
    }
  },
  actions: {
    // 获取基础信息
    async getBaseInfo({ commit, state }) {
      try {
        const next = () => {
          // #ifdef WEB
          document.title = state.baseInfo?.homeTitle || state.pageTitle
          uni.setNavigationBarTitle({ title: state.baseInfo?.homeTitle || state.pageTitle })
          if (uni.$auth.sdk.checkApi("setNavigationBarTitle")) {
            uni.$auth.sdk.setNavigationBarTitle(state.baseInfo?.homeTitle || state.pageTitle)
          }
          // #endif
        }
        next()
        const data = await uni.$api.channel.baseSet({}, { handleError: false, queue: "sync" })
        // #ifdef WEB
        if (!state.baseInfo.umk) {
          data.umk && uni.$loadScript(`https://s9.cnzz.com/z.js?id=${data.umk}`)
        }
        if (data.logo) {
          setWebIcon(data.logo)
        }
        // #endif
        commit("SET_BASE_INFO", data)
        if (data.homeTitle) commit("SET_PAGE_TITLE", data.homeTitle)
        next()

        return Promise.resolve(data)
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 清除基础信息
    clearBaseInfo({ commit }) {
      commit("CLEAR_BASE_INFO")
    }
  }
}
